/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cmti.skeleton.web.controller;

import com.cmti.skeleton.dto.SysLogDto;
import com.cmti.skeleton.dto.SysRoleDto;
import com.cmti.skeleton.entity.SysLog;
import com.cmti.skeleton.entity.SysRights;
import com.cmti.skeleton.entity.SysRole;
import com.cmti.skeleton.service.RoleService;
import com.cmti.skeleton.web.SysLogInterceptor;
import com.github.pagehelper.Page;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author Danny Lee CMTI
 */
@Controller
@RequestMapping("/role")
public class RoleController {

    private final Log log = LogFactory.getLog(this.getClass());
    @Autowired
    private RoleService service;
//    @Autowired
//    private CommonDao commonDao;

    @RequestMapping("/list/ui")
    @RequiresPermissions("role:list:ui")
    public String listUI() {
        return "sys/role";
    }

    @RequestMapping("/list/data")
    @RequiresPermissions("role:list:*")
    public void listData(SysRoleDto role, ModelMap model, HttpSession session) {
        Page<SysRoleDto> page = (Page<SysRoleDto>) service.getRoles(role);
        model.addAttribute("rows", page.getResult())
                .addAttribute("total", page.getTotal());
    }

    /**
     * 使用layui时调用
     *
     * @param role
     * @param model
     * @param session
     */
    @RequestMapping("/list/dataL")
    @RequiresPermissions("role:list:*")
    public void listDataL(SysRoleDto role, ModelMap model, HttpSession session, @RequestParam(value = "limit", defaultValue = "10") int limit) {
        role.setRows(limit);
        Page<SysRoleDto> page = (Page<SysRoleDto>) service.getRoles(role);
        model.addAttribute("code", 0).addAttribute("msg", "").addAttribute("data", page.getResult()).addAttribute("count", page.getTotal());
    }

    @RequestMapping("/list/roleRight")
    @RequiresPermissions("role:list:*")
    public void getRightsByRoleId(@RequestParam("roleId") long roleId, ModelMap model, HttpSession session) {
        model.addAttribute("menu", service.getRightsTreeByRoleId(roleId));
    }

    @RequestMapping("/add/ui")
    @RequiresPermissions("role:add:*")
    public void addUi() {
    }

    @RequestMapping("/add/action")
    @RequiresPermissions("role:add:*")
    public void addAction(SysRoleDto roleDto, ModelMap model, HttpServletRequest request) {
        // 准备日志实例
        StringBuilder logContent = new StringBuilder();
        logContent.append("添加名为 “").append(roleDto.getName()).append("” 的角色信息");
        SysLogDto sysLog = SysLogInterceptor.generateSysLog(request, SysLog.TYPE_OPERATE, logContent.toString());

        try {
            service.addRole(roleDto);
            model.addAttribute("result", true);
        } catch (DuplicateKeyException e) {
            sysLog.setException(e);
            sysLog.setResult(SysLog.RESULT_FAIL);
            model.addAttribute("result", false).addAttribute("msg", "角色名称重复!");
        }
    }

    @RequestMapping("/list/availableRights")
    @RequiresPermissions("role:list:*")
    public void availableRights(ModelMap model, HttpSession session) {
        model.addAttribute("tree", session.getAttribute("rightsTree"));
    }

    @RequestMapping("/delete/ui")
    @RequiresPermissions("role:delete:*")
    public void deleteUi() {
    }

    @RequestMapping("/delete")
    @RequiresPermissions("role:delete:*")
    public void delete(@RequestParam("roleId") long roleId, ModelMap model, HttpServletRequest request) {
        // 准备日志实例
        SysRole roleDto = service.getRoleById(roleId);
        StringBuilder logContent = new StringBuilder();
        logContent.append("删除名为 “").append(roleDto.getName()).append("” 的角色信息");
        SysLog sysLog = SysLogInterceptor.generateSysLog(request, SysLog.TYPE_OPERATE, logContent.toString());

        int i = service.deleteRole(roleId);
        if (i == 0) {
            model.addAttribute("result", true);
        } else if (i == 1) {
            sysLog.setResult(SysLog.RESULT_FAIL);
            model.addAttribute("result", false).addAttribute("msg", "该角色下存在已关联的用户，无法删除!");
        }
    }

    @RequestMapping("/modify/ui")
    @RequiresPermissions(value = {"role:modify:*", "role:detail:*"}, logical = Logical.OR)
    public void modifyUi(@RequestParam("roleId") long roleId, ModelMap model) {
        model.addAttribute("list", service.getRightsByRoleId(roleId));
    }

    @RequestMapping(value = "/detail/ui")
    @RequiresPermissions("role:detail:*")
    public void detailUi() {
    }

    @RequestMapping("/modify/action")
    @RequiresPermissions("role:modify:*")
    public void modifyAction(SysRoleDto roleDto, ModelMap model, HttpServletRequest request) {
        // 准备日志实例
        SysRole role = service.getRoleById(roleDto.getId());
        StringBuilder logContent = new StringBuilder();
        logContent.append("修改名为 “").append(role.getName()).append("” 的角色信息");
        SysLogDto sysLog = SysLogInterceptor.generateSysLog(request, SysLog.TYPE_OPERATE, logContent.toString());
        try {
            service.modifyRole(roleDto);
            model.addAttribute("result", true);
        } catch (DuplicateKeyException e) {
            sysLog.setException(e);
            sysLog.setResult(SysLog.RESULT_FAIL);
            model.addAttribute("result", false).addAttribute("msg", "角色名称重复!");
        }
    }

    @RequestMapping("/modify/lockRole")
    @RequiresPermissions("role:modify:*")
    public void lockUserAction(@RequestParam("roleId") long roleId, @RequestParam("status") Integer status, HttpServletRequest request) {
        // 准备日志实例
        SysRole roleById = service.getRoleById(roleId);
        StringBuilder logContent = new StringBuilder();
        logContent.append("角色").append(roleById.getName());
        if (status == 0) {
            logContent.append("被激活");
        } else if (status == 1) {
            logContent.append("被冻结");
        }
        SysLogInterceptor.generateSysLog(request, SysLog.TYPE_OPERATE, logContent.toString());

        service.lockOrUnlock(roleId, status);
    }

    @RequestMapping("/list/authtree")
    @RequiresPermissions("role:list:*")
    public void authtreeyUi(@RequestParam("loginUserId") long loginUserId, @RequestParam("roleId") long roleId, ModelMap model) {
        model.addAttribute("list", service.getRightsByUserId(loginUserId)).addAttribute("checkedId", service.getRightsByRoleId(roleId));
    }

}
